package com.fengwuj.mutils.aop.function;

import com.fengwuj.mutils.aop.annotation.EnumValue;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;

/**
 * 修订记录：
 * jiangbo 2020/1/7 19:11 创建
 *
 * @author jiangbo
 */
public class EnumValueValidator implements ConstraintValidator<EnumValue, Object> {

    private String[] stringValues;
    private int[] intValues;

    @Override
    public void initialize(EnumValue constraintAnnotation) {
        stringValues = constraintAnnotation.stringValues();
        intValues = constraintAnnotation.intValues();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
        boolean flag = false;
        if (Objects.isNull(value)){
            flag = true;
        }
        if (value instanceof String){
            String valueStr = (String) value;
            if (StringUtils.isBlank(valueStr)){
                flag = true;
            }else {
                for (String strTemp:stringValues){
                    if (strTemp.equals(valueStr)){
                        flag = true;
                        break;
                    }
                }
            }
        }
        if (value instanceof Integer){
            for (Integer intTemp: intValues){
                if (value==intTemp){
                    flag = true;
                    break;
                }
            }
        }
        return flag;
    }
}
